package com.baomidou.mybatisplus.generator.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.dom4j.Element;

public class Util {

	public static Boolean isNotEmpty(String str) {
		if (str != null && str != "") {
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public static List<ColumnTable> getTypeHandlerTable(Element root) {
		List<ColumnTable> result = new ArrayList<>();
		List<Element> tables = root.elements("table");
		if (tables != null && tables.size() != 0) {
			for (Element table : tables) {
				// 获取column节点
				List<Element> columns = table.elements("column");
				if (columns != null && columns.size() != 0) {
					ColumnTable ct = new ColumnTable();
					ct.setTableName(table.attributeValue("name"));
					List<Column> cs = new ArrayList<>();
					for (Element column : columns) {
						Column c = new Column();
						c.setClazz(column.attributeValue("class")).setColumnName(column.getText())
								.setHandlerClass(column.attributeValue("typeHandler"))
								.setJavaType(column.attributeValue("javaType"));
						cs.add(c);
					}
					ct.setColumn(cs);
					result.add(ct);
				}
			}
		}
		return result;
	}

	public static String[] converSetToArray(Set<String> set) {
		return set.toArray(new String[set.size()]);
	}

	public static List<String> sortPackage(Set<String> set) {
		List<String> list = new ArrayList<>(set);
		List<String> resultList = new ArrayList<>();
		Collections.sort(list);
		for (int i = 1; i < list.size(); i++) {
			String s1 = list.get(i);
			String s2 = list.get(i - 1);
			resultList.add(s2);
			if (!s1.substring(0, s1.indexOf(".")).equals(s2.substring(0, s2.indexOf(".")))) {
				resultList.add("");
			}
		}
		resultList.add(list.get(list.size() - 1));
		return resultList;
	}

	public static String fristToLowerCase(String str) {
		return str.substring(0, 1).toLowerCase() + str.substring(1, str.length());
	}

	public static List<String> distinctList(List<String> list) {
		List<String> result = new ArrayList<String>();
		Set<String> set = new HashSet<>();
		if (list != null && list.size() != 0) {
			Iterator<String> it = list.iterator();
			while (it.hasNext()) {
				set.add(it.next());
			}
			result = new ArrayList<String>(set);
		}
		return result;
	}
}
